package com.example.service.serviceImpl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.UserHolder;
import com.example.domain.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.OrdersMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.TypeMapper;
import com.example.mapper.EmpMapper;
import com.example.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class RoomServiceAImpl implements RoomService {

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private OrdersMapper orderMapper;


    @Value("${yun.alioss.access-key-id}")
    private  String accessKeyId;
    @Value("${yun.alioss.access-key-secret}")
    private String accessKeySecret;
    @Value("${yun.alioss.endpoint}")
    private String endpoint;
    @Value("${yun.alioss.bucket-name}")
    private String bucketName;



    @Override
    public List<Room> findAll() {
        return roomMapper.selectList(null);
    }

    @Override
    public Page<Room> findBySearch(Params params) {
        Account user = UserHolder.getUser();
        if("USER".equals(user.getRole())){
            return listOfUser(params);
        }else{
            return listOfAdminAndEmp(params);
        }

    }

    private Page<Room> listOfAdminAndEmp(Params params){
        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<Room>()
                .eq(params.getType() != null, Room.TYPE, params.getType())
                .like(params.getName() != null, Room.NAME, params.getName())
                .eq(params.getDeviceSupport() != null && !params.getDeviceSupport().isEmpty(), Room.DEVICE_SUPPORT, params.getDeviceSupport())
                .orderByDesc("id");
        Page<Room> page = new Page<>(params.getPageNum(), params.getPageSize());
        Page<Room> roomPage = roomMapper.selectPage(page, roomQueryWrapper);
        roomPage.getRecords().forEach(room -> {
            // 设置description
                if (room.getDeviceSupport() != null) {
                    String[] deviceSupport = room.getDeviceSupport().split("-");
                    StringBuilder description = new StringBuilder("该房间最大容纳参会人数:");

                    description.append(room.getSeatNum());
                    description.append(" \n支持以下设备：");

                    if (deviceSupport.length > 0 && "1".equals(deviceSupport[0])) {
                        description.append("\n- 投影仪");
                    }
                    if (deviceSupport.length > 1 && "1".equals(deviceSupport[1])) {
                        description.append("\n- 音响设备");
                    }
                    if (deviceSupport.length > 2 && "1".equals(deviceSupport[2])) {
                        description.append("\n- 网络连接");
                    }
                    room.setDescription(description.toString());
                }
        });
        return roomPage;
    }
    private Page<Room> listOfUser(Params params){
        if (params.getStartTime()!=null) {
            params.setStartTime(params.getStartTime().plusHours(8));
        }
        LocalDateTime startTime = params.getStartTime();
        if (params.getEndTime()!=null) {
            params.setEndTime(params.getEndTime().plusHours(8));
        }
        LocalDateTime endTime = params.getEndTime();

        List<Orders> orderList = null;
        if (startTime != null && endTime != null ){
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.le(Orders.START_TIME, endTime);
            queryWrapper.ge(Orders.END_TIME, startTime);
            orderList = orderMapper.selectList(queryWrapper);
        }else if (startTime == null && endTime == null ){
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.le(Orders.START_TIME, endTime);
            queryWrapper.ge(Orders.END_TIME, startTime);
            orderList = orderMapper.selectList(queryWrapper);
        }

        List<Integer> roomIds = null;
        Map<Integer, Integer> roomIdOfStatus = null;
        if(orderList != null && orderList.size()>0){
            roomIds = orderList.stream().map(c -> c.getRoomId()).collect(Collectors.toList());
            roomIdOfStatus = orderList.stream()
                    .collect(Collectors.toMap(
                            Orders::getRoomId,       // 键：roomId
                            Orders::getStatus,       // 值：status
                            (existing, replacement) -> replacement // 冲突时保留后者
                    ));
        }

        // 查询所有房间
        Account user = UserHolder.getUser();
        String seatNum = params.getSeatNum();

        QueryWrapper<Room> roomQueryWrapper = new QueryWrapper<Room>();
        // 处理座位数范围查询
        if (StringUtils.isNotBlank(seatNum)) {
            String range = seatNum;

            if (range.contains("-")) { // 区间范围，如"0-10"
                String[] parts = range.split("-");
                Integer min = Integer.parseInt(parts[0]);
                Integer max = Integer.parseInt(parts[1]);
                roomQueryWrapper.between("seat_num", min, max);
            } else if (range.contains("及以上")) { // 大于等于，如"40及以上"
                String numStr = range.replace("及以上", "");
                Integer min = Integer.parseInt(numStr);
                roomQueryWrapper.ge("seat_num", min);
            } // 可扩展其他格式，如"以下"
        }

        roomQueryWrapper
                .eq(params.getType() != null, Room.TYPE, params.getType())
                //.eq(user.getRole().equals("USER"), Room.STATUS, 0)
                .like(params.getName() != null, Room.NAME, params.getName())
                .eq(params.getDeviceSupport() != null && !params.getDeviceSupport().isEmpty(), Room.DEVICE_SUPPORT, params.getDeviceSupport())
                .orderByDesc("id");

        // 排除已有订单的房间
//        if (roomIds !=null && !roomIds.isEmpty()) {
//            roomQueryWrapper.notIn(Room.ID, roomIds);
//        }

        List<Room> rooms = roomMapper.selectList(roomQueryWrapper);
        Map<Integer, Integer> filterMap = rooms.stream().collect(Collectors.toMap(Room::getId, Room::getStatus));
        for (Room room : rooms) {
            //一开始全为空闲
            room.setStatus(0);
            if (roomIdOfStatus != null){
                Integer status = roomIdOfStatus.get(room.getId());
                if (status == null) continue;
                if (status == 1){ // 订单状态为1，表示订单待支付，该会议室已被锁定
                    room.setStatus(1);
                }else if(status == 2 || status == 5){ // 订单状态为2，表示订单已支付，该会议室已被预订
                    room.setStatus(2);
                }else{ // 其他情况则房间空闲
                    room.setStatus(0);
                }
            }
        }

//        if("USER".equals(user.getRole())){
//            //  用户只能查看空闲房间
//            rooms = rooms.stream().filter(room -> room.getStatus() == 0).collect(Collectors.toList());
//        }

        // 设置description
        rooms = rooms.stream().map(room -> {
            if (room.getDeviceSupport() != null) {
                String[] deviceSupport = room.getDeviceSupport().split("-");
                StringBuilder description = new StringBuilder("该房间最大容纳参会人数:");

                description.append(room.getSeatNum());
                description.append(" \n支持以下设备：");

                if (deviceSupport.length > 0 && "1".equals(deviceSupport[0])) {
                    description.append("\n- 投影仪");
                }
                if (deviceSupport.length > 1 && "1".equals(deviceSupport[1])) {
                    description.append("\n- 音响设备");
                }
                if (deviceSupport.length > 2 && "1".equals(deviceSupport[2])) {
                    description.append("\n- 网络连接");
                }
                room.setDescription(description.toString());
            }
            return room;
        }).collect(Collectors.toList());

        rooms = rooms.stream().filter(c->{
            Integer status = filterMap.get(c.getId());
            return status == 0 || status == 3;
        }).collect(Collectors.toList());

        // 分页处理
        int pageNum = params.getPageNum();
        int pageSize = params.getPageSize();
        int total = rooms.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<Room> pageList = rooms.subList(fromIndex, toIndex);

        // 创建分页对象
        Page<Room> page = new Page<>(pageNum, pageSize, total);
        page.setRecords(pageList);
        return page;
    }

    @Override
    public void add(Room room) {
        Account user = UserHolder.getUser();
        if (user.getRole().equals("USER")){
            throw new CustomException("权限不足");
        }
        if (room.getName() == null || "".equals(room.getName())) {
            throw new CustomException("名称不能为空");
        }
        room.setStatus(0);
        roomMapper.insert(room);
    }

    @Override
    public void update(Room room) {

        Account user = UserHolder.getUser();
        if (user.getRole().equals("USER")){
            throw new CustomException("权限不足");
        }

        if (room.getName() == null || "".equals(room.getName())) {
            throw new CustomException("分类名称不能为空");
        }

        roomMapper.updateById(room);
    }

    @Override
    public void delete(Integer id) {
        Account user = UserHolder.getUser();
        if (!user.getRole().equals("ADMIN")){
            throw new CustomException("权限不足");
        }
        roomMapper.deleteById(id);
    }

    @Override
    public Room findById(Integer id) {
        return roomMapper.selectById(id);
    }


//    public ResultVO courseResourceUpLoad(Integer courseId, CourseResourceDTO dto) {
//
//        MultipartFile file = dto.getFile();
//
//
//        try {
//            // 获取原始文件名
//            String originalFilename = file.getOriginalFilename();
//            // 截取原始文件名的后缀
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            // 构造新文件名称
//            String objectName = UUID.randomUUID() + extension;
//            // 文件的请求路径
//            String filePath = upload(file.getBytes(), objectName);
//            CourseResourceEntity entity = new CourseResourceEntity();
//            entity.setCourseId(courseId);
//            entity.setPath(filePath);
//            entity.setName(dto.getName());
//            if (videoExtensions.contains(extension)){
//                //说明是视频类型
//                entity.setType(0); // 视频（mp4)
//            }else {
//                entity.setType(1); // 文件（pdf或doc）
//            }
//
//            courseResourceMapper.insert(entity);
//
//            return result(filePath);
//        } catch (IOException e) {
//
//        }
//        return null;
//
//    }
//
//    public String upload(byte[] bytes, String objectName) {
//
//        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//        try {
//            // 创建PutObject请求。
//            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
//        } catch (OSSException oe) {
//            System.out.println("Caught an OSSException, which means your request made it to OSS, "
//                    + "but was rejected with an error response for some reason.");
//            System.out.println("Error Message:" + oe.getErrorMessage());
//            System.out.println("Error Code:" + oe.getErrorCode());
//            System.out.println("Request ID:" + oe.getRequestId());
//            System.out.println("Host ID:" + oe.getHostId());
//        } catch (com.aliyun.oss.ClientException ce) {
//            System.out.println("Caught an ClientException, which means the client encountered "
//                    + "a serious internal problem while trying to communicate with OSS, "
//                    + "such as not being able to access the network.");
//            System.out.println("Error Message:" + ce.getMessage());
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }
//
//        // todo 自定义文件访问路径规则 https://BucketName.Endpoint/ObjectName
//        StringBuilder stringBuilder = new StringBuilder("https://");
//        stringBuilder
//                .append(bucketName)
//                .append(".")
//                .append(endpoint)
//                .append("/")
//                .append(objectName);
//
//        return stringBuilder.toString();
//    }



}